import time

import jwt
from django.http import JsonResponse
from django_redis import get_redis_connection
from rest_framework.views import APIView
from rest_framework_simplejwt.backends import TokenBackend
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from .auth_serializers import CustomTokenObtainPairSerializer, CustomTokenRefreshSerializer
from .auth_utils.auth_utils import generate_captcha

from rest_framework.response import Response


# 自定义登录视图
class CustomTokenObtainPairView(TokenObtainPairView):
    serializer_class = CustomTokenObtainPairSerializer


class CustomTokenRefreshView(TokenRefreshView):
    serializer_class = CustomTokenRefreshSerializer

    def post(self, request, *args, **kwargs):
        # 从查询参数中获取 refreshToken 字段
        refresh_token = request.query_params.get("refreshToken")
        if not refresh_token:
            return Response({"code": "A0241", "msg": "缺少 refreshToken 参数"}, status=400)
        # 构造数据字典，注意必须与序列化器字段名称对应（使用 refresh 字段）
        serializer = self.get_serializer(data={"refresh": refresh_token})
        serializer.is_valid(raise_exception=True)
        return Response(serializer.validated_data)


# 验证码生成视图
class CaptchaView(APIView):
    # @log_api(content="用户获取验证码", module="认证模块")
    @staticmethod
    def get(request, *args, **kwargs):
        captcha_data = generate_captcha()
        response_data = {
            "code": "00000",
            "data": captcha_data,
            "msg": "一切ok"
        }
        return Response(response_data)


class LogoutView(APIView):
    @staticmethod
    def delete(request, *args, **kwargs):  # 移除 @staticmethod 装饰器
        # 获取请求头中的 Authorization 信息
        auth_header = request.headers.get("Authorization")
        if not auth_header or not auth_header.startswith("Bearer "):
            return JsonResponse({"code": "A0250", "msg": "缺少或无效的token"}, status=400)

        # 提取 token 字符串
        token = auth_header.split()[1]

        # 解码 token 获取过期时间
        token_backend = TokenBackend(algorithm="HS256")
        try:
            # 忽略过期时间的验证
            token_data = token_backend.decode(token, verify=False)
        except jwt.DecodeError:
            return JsonResponse({"code": "A0251", "msg": "无效的token"}, status=400)

        now = int(time.time())
        exp = token_data.get("exp", now)
        remaining_seconds = exp - now
        if remaining_seconds <= 0:
            remaining_seconds = 0

        # 将 token 存入 Redis 黑名单中，key 前缀 "blacklist_"
        redis_conn = get_redis_connection("default")
        if remaining_seconds:
            redis_conn.setex(f"blacklist_{token}", remaining_seconds, "1")

        return Response({
            "code": "00000",
            "data": None,
            "msg": "一切ok"
        })
